package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.bean.DimemsionMenu;
import com.example.administrator.yanfoxconn.bean.LMIE8S;
import com.example.administrator.yanfoxconn.bean.LWInfo;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.example.administrator.yanfoxconn.widget.TouchImageView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description IE8S 稽核異常記錄 詳情和改善
 * @Author song
 * @Date 2022/2/19 10:20
 */
public class LWUpActivity extends BaseActivity implements View.OnClickListener {

    private final int MESSAGE_SET_DEP_TYPE=11;
    private final int MESSAGE_SET_PEOPLE_AREA=22;
//    private final int MESSAGE_SET_AREA=33;
    private final int MESSAGE_SET_LOCATION=44;
    private final int MESSAGE_SET_FLOOR=55;
//    private final int MESSAGE_SET_TYPE=66;
    private final int MESSAGE_SET_ITEM=77;


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnUp;//提交
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題

    @BindView(R.id.sp_dep)
    Spinner spDep;//責任單位
    @BindView(R.id.sp_people)
    Spinner spPeople;//責任窗口
    @BindView(R.id.sp_area)
    Spinner spArea;//異常區域
    @BindView(R.id.sp_location)
    Spinner spLocation;//異常位置-樓棟
    @BindView(R.id.sp_floor)
    Spinner spFloor;//異常位置-樓層
    @BindView(R.id.et_address)
    EditText etAddress;//具體位置
    @BindView(R.id.sp_type)
    Spinner spType;//異常類別
    @BindView(R.id.sp_item)
    Spinner spItme;//異常項目
    @BindView(R.id.et_desp)
    EditText etDesp;//問題點描述

    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域
    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;
    private LWUpActivity mContext = this;

    private List<LWInfo> depInfo,peoInfo,areaInfo,locationInfo,floorInfo,typeInfo,itemInfo;//問題类型，責任單位，處理時效
    private String dep,people,area,location,floor,type,item="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lw_up);
        ButterKnife.bind(this);

        btnBack.setOnClickListener(this);
        btnUp.setOnClickListener(this);
        btnUp.setVisibility(View.VISIBLE);
        btnUp.setText("提交");
//
        ivEmptyOne.setOnClickListener(this);
        tvTitle.setText("改善異常");

        getDepAndType();
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gridViewOne.setNumColumns(cols);

        gridViewOne.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePathsOne.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(1); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                    startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(mContext);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePathsOne);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE_ONE);
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_title_left:
                finish();
                break;
            case R.id.btn_title_right:
                if(dep.equals("請選擇")||people.equals("請選擇")||area.equals("請選擇")
                        ||location.equals("請選擇")||floor.equals("請選擇")
                        ||type.equals("請選擇")||item.equals("請選擇")){
                    ToastUtils.showShort(LWUpActivity.this,"請注意各下拉選擇內容");
                }else{
                    upAdd();
                }
                break;
            case R.id.iv_empty1:
                PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(1); // 最多选择照片数量，默认为1
                intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态
                startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
                break;
        }
    }

    //提交新增異常
    private void upAdd() {
        showDialog();
        final String url = Constants.HTTP_LW_UP_AUDIT; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        object.addProperty("supervise_dep",depID);
        object.addProperty("supervise",people);
        object.addProperty("area", area);
        object.addProperty("location",location);
        object.addProperty("floor",floor);
        object.addProperty("address",etAddress.getText().toString());
        object.addProperty("category",type);
        object.addProperty("item",item);
        object.addProperty("audit_name",FoxContext.getInstance().getName());
        object.addProperty("task","");
        object.addProperty("taskNo","");
        object.addProperty("exce_desp",etDesp.getText().toString());
        object.addProperty("project_name","");

        JsonArray photoArray = new JsonArray();

        if (imagePathsOne != null && imagePathsOne.size() != 0) {
            for (int k = 0; k < imagePathsOne.size(); k++) {
                final String pic_path = imagePathsOne.get(k);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path = sign_dir + File.separator + System.currentTimeMillis() + 0 + k + ".jpg";
                Log.e("------_path-------", _path);
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 50);
                Log.e("-------compressImage------", compressImage);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                Log.e("-------picBase64Code-------", "====" + picBase64Code);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("item", (k+1)+"");
                jsonObject1.addProperty("image", picBase64Code);
                photoArray.add(jsonObject1);
            }
        } else {
        }
        object.add("photoList", photoArray);
        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("code").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("msg").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
//                case MESSAGE_TOAST://Toast彈出
//
//                    break;
                case Constants.MESSAGE_NETMISTAKE://Toast彈出
                    ToastUtils.showLong(LWUpActivity.this,R.string.net_mistake);
                    break;
                case Constants.MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),1);
                    break;
                case Constants.MESSAGE_ALERT:
                    aboutAlert(msg.obj.toString(),1);
                    break;
                case MESSAGE_SET_DEP_TYPE:
                    setDepAndType();
                    break;
                case MESSAGE_SET_PEOPLE_AREA:
                    setPeoAndArea();
                    break;
                case MESSAGE_SET_LOCATION:
                    setLocation();
                    break;
                case MESSAGE_SET_FLOOR:
                    setFloor();
                    break;
                case MESSAGE_SET_ITEM:
                    setItem();
                    break;

            }
            super.handleMessage(msg);
        }
    };


    List<String> getDepList,getPeoList,getTypeList,getItemList;
    List<String>  getAreaList,getLocationList,getFloorList;
    String result;
    String depID,typeCode;
    //獲取責任單位和巡檢類別
    private void getDepAndType(){
        showDialog();
        final String url = Constants.HTTP_LW_GET_DEP;
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray arrayDep = jsonObject.get("DepData").getAsJsonArray();
                        depInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayDep) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            depInfo.add(humi);
                        }
                        JsonArray arrayType = jsonObject.get("TypeData").getAsJsonArray();
                        typeInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayType) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            typeInfo.add(humi);
                        }

                        Message message = new Message();
                        message.what = MESSAGE_SET_DEP_TYPE;
                        mHandler.sendMessage(message);

                    }
                }
            }
        }.start();


    }
    private void setDepAndType(){
        //責任單位
        getDepList=new ArrayList<>();
        getDepList.add("請選擇");
        for (int i = 0;i<depInfo.size();i++){
            getDepList.add(depInfo.get(i).getSupervise_dep());
        }
        //下拉列表選擇
        spDep.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getDepList));
        spDep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dep=getDepList.get(position);
                if (!dep.equals("請選擇")){
                    depID=depInfo.get(position-1).getType();
                    getPeoAndArea(depID);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //異常類別
        getTypeList=new ArrayList<>();
        getTypeList.add("請選擇");
        for (int i = 0;i<typeInfo.size();i++){
            getTypeList.add(typeInfo.get(i).getItem_name());
        }
        //下拉列表選擇
        spType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getTypeList));
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type=getTypeList.get(position);
                if (!type.equals("請選擇")){

                    typeCode=typeInfo.get(position-1).getItem_code();
                    getItem(typeCode);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    //根據單位編號，獲取窗口和區域
    private void getPeoAndArea(String depID){
        showDialog();
        final String url = Constants.HTTP_LW_GET_PEO_AREA+"?type="+depID;
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray arrayPeo = jsonObject.get("SuperviseData").getAsJsonArray();
                        peoInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayPeo) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            peoInfo.add(humi);
                        }
                        JsonArray arrayArea = jsonObject.get("AreaData").getAsJsonArray();
                        areaInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayArea) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            areaInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_PEOPLE_AREA;
                        mHandler.sendMessage(message);
                    }
                }
            }
        }.start();
    }
    private void setPeoAndArea(){
        //責任窗口
        getPeoList=new ArrayList<>();
        getPeoList.add("請選擇");
        for (int i = 0;i<peoInfo.size();i++){
            getPeoList.add(peoInfo.get(i).getSupervise_name());
        }
        //下拉列表選擇
        spPeople.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getPeoList));
        spPeople.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                people=getPeoList.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        //異常區域
        getAreaList=new ArrayList<>();
        getAreaList.add("請選擇");
        for (int i = 0;i<areaInfo.size();i++){
            getAreaList.add(areaInfo.get(i).getArea());
        }
        //下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getAreaList));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                area=getAreaList.get(position);
                if (!area.equals("請選擇")){
                    getLocation(depID,area);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    private String url = "";
    //根據單位編號和區域，獲取位置
    private void getLocation(String depID,String area){
        showDialog();
//        try {
//            String area1 =  URLEncoder.encode(URLEncoder.encode(area, "UTF-8"), "UTF-8");
//            url = Constants.HTTP_LW_GET_LOCATION+"?type="+depID+"&area="+area1;
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        url = Constants.HTTP_LW_GET_LOCATION+"?type="+depID+"&area="+area;
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray arrayLocation = jsonObject.get("data").getAsJsonArray();
                        locationInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayLocation) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            locationInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_LOCATION;
                        mHandler.sendMessage(message);
                    }
                }
            }
        }.start();
    }
    private void setLocation(){
        //異常位置
        getLocationList=new ArrayList<>();
        getLocationList.add("請選擇");
        for (int i = 0;i<locationInfo.size();i++){
            getLocationList.add(locationInfo.get(i).getLocation());
        }
        //下拉列表選擇
        spLocation.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getLocationList));
        spLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                location=getLocationList.get(position);
                if (!location.equals("請選擇")){
                    getFloor(depID,area,location);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    //根據責任單位編號和區域和位置，獲取樓層
    private void getFloor(String depID,String area,String location){
        showDialog();
//        try {
//            String area1 =  URLEncoder.encode(URLEncoder.encode(area, "UTF-8"), "UTF-8");
//            String location1 =  URLEncoder.encode(URLEncoder.encode(location, "UTF-8"), "UTF-8");
//            url = Constants.HTTP_LW_GET_LOCATION+"?type="+depID+"&area="+area1+"&location="+location1;
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }

        url = Constants.HTTP_LW_GET_FLOOR+"?type="+depID+"&area="+area+"&location="+location;
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray arrayFloor = jsonObject.get("data").getAsJsonArray();
                        floorInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayFloor) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            floorInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_FLOOR;
                        mHandler.sendMessage(message);
                    }
                }
            }
        }.start();
    }
    private void setFloor(){
        getFloorList=new ArrayList<>();
        getFloorList.add("請選擇");
        for (int i = 0;i<floorInfo.size();i++){
            getFloorList.add(floorInfo.get(i).getFloor());
        }
        //下拉列表選擇
        spFloor.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getFloorList));
        spFloor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                floor=getFloorList.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
    //根據巡檢類別編碼，獲取異常項目
    private void getItem(String flag){
        showDialog();
        final String url = Constants.HTTP_LW_GET_ITEM+"?flag="+flag; //此處寫上自己的URL
        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                result = HttpUtils.queryStringForGet(url);

                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                String response = result;
                dismissDialog();
                if (result != null) {
                    Log.e("---------", "result==fff===" + response);
                    JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                    String errCode = jsonObject.get("code").getAsString();
                    if (errCode.equals("200")) {

                        JsonArray arrayItem = jsonObject.get("data").getAsJsonArray();
                        itemInfo = new ArrayList<LWInfo>();
                        for (JsonElement type1 : arrayItem) {
                            LWInfo humi = gson.fromJson(type1, LWInfo.class);
                            itemInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_ITEM;
                        mHandler.sendMessage(message);
                    }
                }
            }
        }.start();
    }
    private void setItem(){
        getItemList=new ArrayList<>();
        getItemList.add("請選擇");
        for (int i = 0;i<itemInfo.size();i++){
            getItemList.add(itemInfo.get(i).getItem_name());
        }
        //下拉列表選擇
        spItme.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, getItemList));
        spItme.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                item=getItemList.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    private void aboutAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==1){

                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==1){
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();
                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);
        if (paths.size() > 0) {
                ivEmptyOne.setVisibility(View.GONE);
        } else {
                ivEmptyOne.setVisibility(View.VISIBLE);
        }
        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
                gridViewOne.setAdapter(gridAdapterOne);
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 1) {
                return 1;
            } else {
                return listUrls.size() + 1;
            }
        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 1) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }
}
